import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class MethodChannelPage extends StatefulWidget {
  const MethodChannelPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return MethodChannelPageState();
  }
}

class MethodChannelPageState extends State<MethodChannelPage> {


  //代码清单9-1-1
  //创建MethodChannel
  // 参数一 flutter_and_native_101 为通信标识
  // 参数二 codec 为参数传递的 编码方式，非必选 默认 StandardMessageCodec()
  // 参数三  binaryMessenger 为使用的消息通道默认为
  //    [ServicesBinding.defaultBinaryMessenger]
  static const methodChannel = MethodChannel('flutter_and_native_101');

  //封装 Flutter 向 原生中 发送消息 的方法
  static Future<dynamic> invokNative({
    required String method, //method 为方法标识
    Map<String, dynamic>? arguments, //arguments 为传递的参数
  }) async {
    if (arguments == null) {
      //无参数发送消息
      return await methodChannel.invokeMethod(method);
    } else {
      //有参数发送消息
      return await methodChannel.invokeMethod(method, arguments);
    }
  }
  //代码块9-1-3
  //lib/MethodChannelPage.dart
  @override
  void initState() {
    super.initState();
    ///设置监听
    methodChannel.setMethodCallHandler((MethodCall call) async{
      //处理原生 Android iOS 发送过来的消息
      String method = call.method;
      Map arguments = call.arguments;
      int code = arguments["code"];
      String message = arguments["message"];
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [buildTextButton()],
        ),
      ),
    );
  }

  ///代码清单9-1-2
  String _result = "";

  buildTextButton() {
    return TextButton(
      onPressed: () async {
        //发送消息
        dynamic result = await invokNative(method: "test");
        //回执消息
        if (result != null) {
          _result = result['message'].toString();
          setState(() {});
        }
      },
      child: Text("发送消息 $_result"),
    );
  }
}
